package org.yunai.swjg.server.module.player.operation;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.swjg.server.core.service.OnlineState;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.yfserver.async.IIoSerialOperation;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 角色相关信息加载操作<br />
 * 实际登录流程：
 * <pre>
 *     1. 角色信息加载{@link org.yunai.swjg.server.module.player.vo.Player#onLoad()}
 *     2. 角色信息初始化{@link org.yunai.swjg.server.module.player.vo.Player#onInit()}
 *     3. 角色最终登录并发送所有信息给客户端{@link org.yunai.swjg.server.module.player.vo.Player#onLogin()}
 * </pre>
 * User: yunai
 * Date: 13-4-5
 * Time: 下午6:03
 */
public class PlayerInfoLoadOperation implements IIoSerialOperation {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.player, PlayerLoadOperation.class);

    private static OnlineContextService onlineContextService;

    static {
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
    }

    private volatile Online online;
    /**
     * 被加载数据的玩家编号
     */
    private final Integer playerId;

    /**
     * 加载数据结果
     */
    private volatile boolean success = false;

    public PlayerInfoLoadOperation(Online online, Integer playerId) {
        this.online = online;
        this.playerId = playerId;
    }

    @Override
    public State doStart() {
//        session.getOnline().setState(OnlineState.load_roleing);
        return State.STARTED;
    }

    @Override
    public State doIo() {
        if (online.isConnected()) {
            try {
                // 初始化
                online.init();
                // 加载数据
                Player player = new Player(online);
                player.onLoad();
                // 初始化
                player.onInit();
                success = true;
            } catch (Exception e) {
                LOGGER.error("[doIo] [exception: {}].", ExceptionUtils.getStackTrace(e));
                success = false;
            }
        }
        return State.IO_DONE;
    }

    @Override
    public State doFinish() {
        if (success) {
            // 切换状态
            online.setState(OnlineState.load_roled);
            // 添加到onlineContextService
            onlineContextService.addPlayer(online);
            // 玩家登录初始化
            online.getPlayer().onLogin();
        } else {
            online.disconnect();
        }
        return State.FINISHED;
    }

    @Override
    public Integer getSerialKey() {
        return playerId;
    }
}
